package com.shayu.aicodemother.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.shayu.aicodemother.exception.ErrorCode;
import com.shayu.aicodemother.exception.ThrowUtils;
import com.shayu.aicodemother.manager.CosManager;
import com.shayu.aicodemother.service.ScreenshotService;
import com.shayu.aicodemother.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class ScreenshotServiceImpl implements ScreenshotService {

    @Resource
    private CosManager cosManager;

    /**
     * 截图保存并上传到cos
     *
     * @param webUrl 网址
     * @return
     */
    @Override
    public String generateAndUploadScreenshot(String webUrl) {
        //参数校验
        ThrowUtils.throwIf(StrUtil.isBlank(webUrl), ErrorCode.NOT_FOUND_ERROR, "网页URL不能为空");
        log.info("开始生成网页截图，URL:{}", webUrl);
        //本地截图
        String localScreenshotPath = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
        ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.NOT_FOUND_ERROR, "保存截图的地址不存在");
        try {
            //上传截图到cos
            String cosUrl = uploadScreenshotToCos(localScreenshotPath);
            ThrowUtils.throwIf(StrUtil.isBlank(cosUrl),ErrorCode.OPERATION_ERROR,"截图保存到cos失败，请重试");
            log.info("截图上传成功，URL：{}", cosUrl);
            return cosUrl;
        }finally {
            //删除本地文件
            cleanupLocalFile(localScreenshotPath);
        }
    }


    /**
     * 上传截图到对象存储
     *
     * @param localScreenshotPath 本地截图路径
     * @return 对象存储访问URL，失败返回null
     */
    private String uploadScreenshotToCos(String localScreenshotPath) {

        //参数校验
        if (StrUtil.isBlank(localScreenshotPath)) {
            return null;
        }
        File screenshotFile = new File(localScreenshotPath);
        if (!screenshotFile.exists()) {
            log.error("截图文件不存在：{}", localScreenshotPath);
            return null;
        }
        //生成cos对象键
        String filename = UUID.randomUUID().toString().substring(0, 8) + "_compressed.jpg";
        String cosKey = generateScreenshotKey(filename);
        //上传
        return cosManager.uploadFile(cosKey, screenshotFile);
    }

    /**
     * 生成截图的对象存储键
     *
     * @param filename 格式:/screenshots/2025/8/31/filename.jpg
     * @return
     */
    private String generateScreenshotKey(String filename) {

        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("/screenshots/%s/%s", datePath, filename);

    }

    /**
     *清理本地截图文件
     * @param localScreenshotPath
     */
    private void cleanupLocalFile(String localScreenshotPath) {
        File localFile = new File(localScreenshotPath);
        ThrowUtils.throwIf(!localFile.exists(),ErrorCode.NOT_FOUND_ERROR,"截图文件不存在");
        FileUtil.del(localFile);
        log.info("清理本地文件成功: {}", localScreenshotPath);

    }
}
